﻿using Net35.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Net35.Xrm.Sdk
{
	public static class IOrganizationServiceExtensions
	{
		public static EntityCollection RetrieveAllPages(this IOrganizationService crm, QueryExpression query, int startPage = 1)
		{
			EntityCollection allRecords = new EntityCollection();
			query.PageInfo.PageNumber = Math.Max(1, startPage);
			query.PageInfo.PagingCookie = string.Empty;
			do
			{
				EntityCollection results = crm.RetrieveMultiple(query);
				if (results != null && results.Entities != null && results.Entities.Count > 0)
				{
					allRecords.Entities.AddRange(results.Entities);
				}
				else
					break;
				if (results.MoreRecords)
				{
					query.PageInfo.PagingCookie = results.PagingCookie;
					query.PageInfo.PageNumber++;
				}
				else
					break;
			} while (true);
			return allRecords;
		}
	}
}
